import React, { useRef, useState } from 'react';
import { PageContainer, ProTable } from '@ant-design/pro-components';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import { Button, Space, Tag, Popconfirm, message, Modal, Dropdown, Typography, Switch, Badge } from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined, MoreOutlined, EyeOutlined, TrophyOutlined } from '@ant-design/icons';
import { getAchievementList, deleteAchievement, updateAchievementStatus } from '@/services/systemManagementApi';
import AchievementForm from './components/AchievementForm';
import AchievementDetail from './components/AchievementDetail';
import moment from 'moment';

const { Text } = Typography;

const AchievementList: React.FC = () => {
  const actionRef = useRef<ActionType>();
  const [selectedRowKeys, setSelectedRowKeys] = useState<number[]>([]);
  const [achievementFormVisible, setAchievementFormVisible] = useState(false);
  const [achievementDetailVisible, setAchievementDetailVisible] = useState(false);
  const [currentAchievement, setCurrentAchievement] = useState<SYSTEM.AchievementDefinitionModel | undefined>();
  const [editMode, setEditMode] = useState<'create' | 'edit'>('create');

  // 成就类型标签颜色映射
  const typeColorMap = {
    learning: 'blue',
    social: 'green',
    challenge: 'orange',
    special: 'purple',
  };

  // 条件类型标签颜色映射
  const conditionTypeColorMap = {
    course_complete: 'cyan',
    login_days: 'geekblue',
    score_achieve: 'magenta',
    share_count: 'lime',
    comment_count: 'gold',
  };

  // 表格列定义
  const columns: ProColumns<SYSTEM.AchievementDefinitionModel>[] = [
    {
      title: 'ID',
      dataIndex: 'id',
      width: 60,
      search: false,
    },
    {
      title: '成就图标',
      dataIndex: 'icon_url',
      width: 80,
      search: false,
      render: (iconUrl) => (
        <div style={{
          width: 48,
          height: 48,
          background: iconUrl ? `url(${iconUrl}) center/cover` : '#f5f5f5',
          borderRadius: 8,
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'center',
          border: '1px solid #d9d9d9'
        }}>
          {!iconUrl && <TrophyOutlined style={{ color: '#999' }} />}
        </div>
      ),
    },
    {
      title: '成就名称',
      dataIndex: 'name',
      width: 150,
      ellipsis: true,
      render: (text) => (
        <Text style={{ maxWidth: 130 }} ellipsis={{ tooltip: text }}>
          {text}
        </Text>
      ),
    },
    {
      title: '成就描述',
      dataIndex: 'description',
      width: 200,
      search: false,
      ellipsis: true,
      render: (desc) => (
        <Text type="secondary" style={{ maxWidth: 180 }} ellipsis={{ tooltip: desc }}>
          {desc}
        </Text>
      ),
    },
    {
      title: '成就类型',
      dataIndex: 'type',
      width: 100,
      valueType: 'select',
      valueEnum: {
        learning: { text: '学习成就', status: 'Processing' },
        social: { text: '社交成就', status: 'Success' },
        challenge: { text: '挑战成就', status: 'Warning' },
        special: { text: '特殊成就', status: 'Error' },
      },
      render: (_, record) => {
        const typeMap = {
          learning: '学习成就',
          social: '社交成就',
          challenge: '挑战成就',
          special: '特殊成就',
        };
        return (
          <Tag color={typeColorMap[record.type]}>
            {typeMap[record.type]}
          </Tag>
        );
      },
    },
    {
      title: '触发条件',
      dataIndex: 'condition_type',
      width: 120,
      valueType: 'select',
      valueEnum: {
        course_complete: { text: '完成课程', status: 'Default' },
        login_days: { text: '连续登录', status: 'Processing' },
        score_achieve: { text: '分数达成', status: 'Warning' },
        share_count: { text: '分享次数', status: 'Success' },
        comment_count: { text: '评论次数', status: 'Error' },
      },
      render: (_, record) => {
        const conditionMap = {
          course_complete: '完成课程',
          login_days: '连续登录',
          score_achieve: '分数达成',
          share_count: '分享次数',
          comment_count: '评论次数',
        };
        return (
          <Tag color={conditionTypeColorMap[record.condition_type]}>
            {conditionMap[record.condition_type]}
          </Tag>
        );
      },
    },
    {
      title: '条件值',
      dataIndex: 'condition_value',
      width: 80,
      search: false,
      render: (value, record) => {
        const unitMap = {
          course_complete: '门',
          login_days: '天',
          score_achieve: '分',
          share_count: '次',
          comment_count: '次',
        };
        return `${value}${unitMap[record.condition_type] || ''}`;
      },
    },
    {
      title: '奖励积分',
      dataIndex: 'reward_points',
      width: 80,
      search: false,
      render: (points) => (
        <Badge count={points} style={{ backgroundColor: '#52c41a' }} />
      ),
    },
    {
      title: '获得人数',
      dataIndex: 'achieved_count',
      width: 80,
      search: false,
      render: (count) => (
        <Text type={count > 0 ? 'success' : 'secondary'}>
          {count || 0}
        </Text>
      ),
    },
    {
      title: '状态',
      dataIndex: 'is_active',
      width: 80,
      valueType: 'select',
      valueEnum: {
        true: { text: '启用', status: 'Success' },
        false: { text: '禁用', status: 'Default' },
      },
      render: (_, record) => (
        <Switch
          checked={record.is_active}
          size="small"
          onChange={(checked) => handleStatusChange(record, checked)}
        />
      ),
    },
    {
      title: '创建时间',
      dataIndex: 'created_at',
      width: 160,
      search: false,
      valueType: 'dateTime',
      sorter: true,
    },
    {
      title: '操作',
      valueType: 'option',
      width: 150,
      fixed: 'right',
      render: (_, record) => [
        <Button
          key="detail"
          type="link"
          size="small"
          onClick={() => handleDetail(record)}
        >
          详情
        </Button>,
        <Dropdown
          key="more"
          menu={{
            items: [
              {
                key: 'edit',
                label: '编辑',
                icon: <EditOutlined />,
                onClick: () => handleEdit(record),
              },
              {
                key: 'toggle',
                label: record.is_active ? '禁用' : '启用',
                onClick: () => handleStatusChange(record, !record.is_active),
              },
              {
                type: 'divider',
              },
              {
                key: 'delete',
                label: '删除',
                icon: <DeleteOutlined />,
                danger: true,
                onClick: () => handleDelete(record),
              },
            ],
          }}
        >
          <Button type="link" size="small">
            <MoreOutlined />
          </Button>
        </Dropdown>,
      ],
    },
  ];

  // 处理详情查看
  const handleDetail = (record: SYSTEM.AchievementDefinitionModel) => {
    setCurrentAchievement(record);
    setAchievementDetailVisible(true);
  };

  // 处理编辑
  const handleEdit = (record: SYSTEM.AchievementDefinitionModel) => {
    setCurrentAchievement(record);
    setEditMode('edit');
    setAchievementFormVisible(true);
  };

  // 处理状态切换
  const handleStatusChange = async (record: SYSTEM.AchievementDefinitionModel, checked: boolean) => {
    try {
      await updateAchievementStatus(record.id, checked);
      message.success(`成就${checked ? '启用' : '禁用'}成功`);
      actionRef.current?.reload();
    } catch (error) {
      message.error(`成就${checked ? '启用' : '禁用'}失败`);
    }
  };

  // 处理删除
  const handleDelete = (record: SYSTEM.AchievementDefinitionModel) => {
    Modal.confirm({
      title: '确认删除',
      content: `确定要删除成就 "${record.name}" 吗？此操作不可恢复。`,
      okText: '确认',
      cancelText: '取消',
      okType: 'danger',
      onOk: async () => {
        try {
          await deleteAchievement(record.id);
          message.success('删除成功');
          actionRef.current?.reload();
        } catch (error) {
          message.error('删除失败');
        }
      },
    });
  };

  // 处理新建
  const handleCreate = () => {
    setCurrentAchievement(undefined);
    setEditMode('create');
    setAchievementFormVisible(true);
  };

  return (
    <PageContainer>
      <ProTable<SYSTEM.AchievementDefinitionModel>
        headerTitle="成就管理"
        actionRef={actionRef}
        rowKey="id"
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => [
          <Button
            key="create"
            type="primary"
            icon={<PlusOutlined />}
            onClick={handleCreate}
          >
            新建成就
          </Button>,
        ]}
        request={async (params, sort) => {
          const response = await getAchievementList({
            page: params.current,
            limit: params.pageSize,
            keyword: params.name,
            type: params.type,
            condition_type: params.condition_type,
            is_active: params.is_active,
          });
          return {
            data: response.data.list,
            success: response.code === 200,
            total: response.data.pagination.total,
          };
        }}
        columns={columns}
        rowSelection={{
          selectedRowKeys,
          onChange: (keys) => setSelectedRowKeys(keys as number[]),
        }}
        scroll={{ x: 1400 }}
        pagination={{
          defaultPageSize: 20,
          showSizeChanger: true,
          showQuickJumper: true,
        }}
      />

      {/* 成就表单弹窗 */}
      <AchievementForm
        visible={achievementFormVisible}
        mode={editMode}
        initialValues={currentAchievement}
        onCancel={() => setAchievementFormVisible(false)}
        onSuccess={() => {
          setAchievementFormVisible(false);
          actionRef.current?.reload();
        }}
      />

      {/* 成就详情弹窗 */}
      <AchievementDetail
        visible={achievementDetailVisible}
        achievement={currentAchievement}
        onCancel={() => setAchievementDetailVisible(false)}
      />
    </PageContainer>
  );
};

export default AchievementList;
